package com.system.database;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Order(-1)
@Component
public class DynamicDataSourceAspect {
	@Around("@within(DS)|| @annotation(DS)")
	public Object aroundSwitchDs(ProceedingJoinPoint point) throws Throwable{
		String dataSource = DataSourceContextHolder.DEFAULT_DS;
		// 获取切入的 Method
        MethodSignature joinPointObject = (MethodSignature) point.getSignature();
        Method method = joinPointObject.getMethod();

        boolean flag = method.isAnnotationPresent(DS.class);
        if (flag) {
        	DS annotation = method.getAnnotation(DS.class);
        	dataSource =  annotation.value();
        } else {
            // 如果方法上没有注解，则搜索类上是否有注解
        	DS classAnnotation = AnnotationUtils.findAnnotation(method.getDeclaringClass(), DS.class);
            if (classAnnotation != null) {
            	dataSource = classAnnotation.value();
            }
        }
	    // 切换数据源
	    DataSourceContextHolder.setDB(dataSource);
	    Object o = null;
		try {
			o = point.proceed();
		} catch (Throwable e) {
			DataSourceContextHolder.clearDB();
			throw e;
		}
		//用后清空
		DataSourceContextHolder.clearDB();
		return o;
	}
}
